package com.hy.net.interceptor;

import com.hy.net.annotation.Timeout;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Invocation;

/**
 * 超时拦截器 - 动态配置HTTP请求超时时长
 *
 * @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
 */
public class TimeoutInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Invocation invocation = request.tag(Invocation.class);
        if (invocation != null) {
            Timeout timeout = invocation.method().getAnnotation(Timeout.class);
            if (timeout != null) {
                return chain.withConnectTimeout(timeout.connectTimeout(), timeout.timeUnit())
                        .withReadTimeout(timeout.readTimeout(), timeout.timeUnit())
                        .withWriteTimeout(timeout.writeTimeout(), timeout.timeUnit())
                        .proceed(request);
            }
        }
        return chain.proceed(chain.request());
    }

}
